package com.qupai.lib_base.widget.sticker

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.qupai.lib_base.utils.GlobalThreadPools

/**
 * 作者：ZhouYou
 * 日期：2016/12/2.
 */
class StickerLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
    private var context: Context? = null

    // 贴纸的集合
    private var stickerViews: MutableList<StickerView?>? = null

    // 贴纸的View参数
    private var stickerParams: LayoutParams? = null

    // 背景图片控件
    private var ivImage: ImageView? = null

    // 旋转操作图片
    private var rotateRes = 0

    // 缩放操作图片
    private var zoomRes = 0

    // 缩放操作图片
    private var removeRes = 0

    //原图
    private var bitmap: Bitmap? = null

    //原图和操作图比例
    private var scale = 0f

    init {
        init(context)
    }

    private fun init(context: Context) {
        this.context = context
        stickerViews = ArrayList()
        stickerParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        addBackgroundImage()
    }

    fun setScale(scale: Float) {
        this.scale = scale
    }

    fun getBitmap(): Bitmap {
        ivImage!!.isDrawingCacheEnabled = true
        val bitmap: Bitmap = Bitmap.createBitmap(ivImage!!.drawingCache)
        ivImage!!.isDrawingCacheEnabled = false
        return bitmap
    }

    /**
     * 清空缓存
     */
    fun refreshBitmap() {
        ivImage!!.refreshDrawableState()
    }

    /**
     * 初始化背景图片控件
     */
    private fun addBackgroundImage() {
        val bgParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        ivImage = ImageView(context)
        ivImage!!.scaleType = ImageView.ScaleType.CENTER_INSIDE
        ivImage!!.layoutParams = bgParams
        addView(ivImage)
    }

    /**
     * 设置背景图片
     */
    fun setBackgroundImage(resource: Int) {
        ivImage!!.setImageResource(resource)
    }

    fun setBackgroundBitmap(bitmap: Bitmap?) {
        this.bitmap = bitmap
        ivImage!!.setImageBitmap(bitmap)
    }

    fun deleteStickerViews() {
        for (view in stickerViews!!) {
            removeView(view)
        }
    }

    /**
     * 新增贴纸
     */
    fun addSticker(resource: Int) {
        val bitmap = BitmapFactory.decodeResource(context!!.resources, resource)
        addSticker(bitmap, true)
    }

    fun addSticker(url: String?) {
        if(url.isNullOrEmpty()){
            LogUtils.e("贴纸图片错误：贴图地址null")
            return
        }
        GlobalThreadPools.getInstance().execute {
            try {
                var bitmap = Glide.with(this)
                    .asBitmap()
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .submit()
                    .get()
                post {
                    addSticker(bitmap, true)
                }
            }catch (e:java.lang.Exception){
                LogUtils.e("贴纸图片错误："+e.message, " url = $url")
            }
        }
    }

    fun addSticker(resource: Int, isShowDelete: Boolean) {
        val bitmap = BitmapFactory.decodeResource(context!!.resources, resource)
        addSticker(bitmap, isShowDelete)
    }

    /**
     * 新增贴纸
     */
    private fun addSticker(bitmap: Bitmap, isShowDelete: Boolean) {
        val sv = StickerView(Utils.getApp())
        sv.setImageBitmap(bitmap)
        sv.layoutParams = stickerParams
        sv.setOnStickerActionListener(object : OnStickerActionListener {
            override fun onDelete() {
                // 处理删除操作
                removeView(sv)
                stickerViews!!.remove(sv)
                redraw()
            }

            override fun onEdit(stickerView: StickerView?) {
                val position = stickerViews!!.indexOf(stickerView)
                stickerView!!.setEdit(true)
                stickerView.bringToFront()
                val size = stickerViews!!.size
                for (i in 0 until size) {
                    val item = stickerViews!![i] ?: continue
                    if (position != i) {
                        item.setEdit(false)
                    }
                }
                //更换位置
                if (position == -1) {
                    return
                }
                stickerViews!!.removeAt(position)
                stickerViews!!.add(stickerView)
            }
        })
        addView(sv)
        stickerViews!!.add(sv)
        redraw()
    }

    /**
     * 查看贴纸的预览操作
     */
    val preview: Unit
        get() {
            for (item in stickerViews!!) {
                if (item == null) {
                    continue
                }
                item.setEdit(false)
            }
        }
    /**
     * 重置贴纸的操作列表
     */
    /**
     * 重置贴纸的操作列表
     */
    private fun redraw(isNotGenerate: Boolean = true) {
        val size = stickerViews!!.size
        if (size <= 0) {
            return
        }
        for (i in size - 1 downTo 0) {
            val item = stickerViews!![i] ?: continue
            item.setZoomRes(zoomRes)
            item.setRotateRes(rotateRes)
            item.setRemoveRes(removeRes)
            if (i == size - 1) {
                item.setEdit(isNotGenerate)
            } else {
                item.setEdit(false)
            }
            stickerViews!![i] = item
        }
    }

    /**
     * 生成合成图片
     *
     * @return
     */
    fun generateCombinedBitmap(): Bitmap {
        redraw(false)
        val dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(dst)
        draw(canvas)
        //        BitmapDrawable draw = (BitmapDrawable) ivImage.getDrawable();
//        Bitmap dst = draw.getBitmap();
        return dst
    }

    // 保存画布
    /**
     * @return 保存原尺寸图片
     */
    val combinedBitmap: Bitmap
        get() {
            val bitmapPaint = Paint()
            bitmapPaint.isAntiAlias = true
            val resultBitmap = bitmap!!.copy(bitmap!!.config, true)
            val canvas = Canvas(resultBitmap)
            canvas.drawBitmap(resultBitmap, 0f, 0f, bitmapPaint)
            for (view in stickerViews!!) {
                LogUtils.i("stickerViews:" + stickerViews!!.size)
                val matrix = view!!.sticker.matrix
                //原图和模板图的比例
                matrix.postScale(scale, scale)
                canvas.drawBitmap(view.sticker.srcImage!!, matrix, bitmapPaint)
            }
            canvas.save() // 保存画布
            canvas.restore()
            return resultBitmap
        }

    fun setRotateRes(rotateRes: Int) {
        this.rotateRes = rotateRes
    }

    fun setZoomRes(zoomRes: Int) {
        this.zoomRes = zoomRes
    }

    fun setRemoveRes(removeRes: Int) {
        this.removeRes = removeRes
    }
}